package org.anachronos.jeep.model.trace.util;

import org.anachronos.jeep.model.trace.DocumentRoot;
import org.anachronos.jeep.model.trace.Invocation;
import org.anachronos.jeep.model.trace.MethodInvocation;
import org.anachronos.jeep.model.trace.Metrics;
import org.eclipse.emf.ecore.EObject;

public class MetricsHelper {
	private MetricsHelper() {
		// prevent instantiation
	}
	
	public static double getTotalTimePercent(final EObject element) {
		final long totalTimeNs = getMetrics(element).getTotalTimeNs();
		final long mergedTotalTimeNs = getMergedMetrics(element).getTotalTimeNs();
		final double timePercent = ((double) totalTimeNs) / mergedTotalTimeNs;
		return timePercent;
	}
	
	public static double getSelfTimePercent(final EObject element) {
		final long totalTimeNs = getMetrics(element).getTotalTimeNs();
		final long mergedTotalTimeNs = getMergedMetrics(element).getTotalTimeNs();
		final double timePercent = ((double) totalTimeNs) / mergedTotalTimeNs;
		return timePercent;
	}

	public static Metrics getMergedMetrics(final EObject element) {
		Metrics mergedMetrics = null;
		if (element instanceof Invocation) {
			final DocumentRoot documentRoot = (DocumentRoot) element.eResource().getContents().get(0);
			mergedMetrics = documentRoot.getTrace().getMergedCallStack().getMetrics();
		}
		return mergedMetrics;
	}

	public static Metrics getMetrics(final EObject element) {
		if (element instanceof Invocation) {
			final Invocation invocation = (Invocation) element;
			return invocation.getMetrics();
		}
		return null;
	}

	public static Metrics getSelfMetrics(final EObject element) {
		if (element instanceof MethodInvocation) {
			final MethodInvocation methodInvocation = (MethodInvocation) element;
			return methodInvocation.getSelfMetrics();
		} else {
			return getMetrics(element);
		}
	}
}
